package echat.future.cn.echat.home

import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.support.v4.widget.NestedScrollView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions.bitmapTransform
import com.google.gson.Gson
import com.zhusx.core.adapter._BasePagerAdapter
import com.zhusx.core.app._BaseAppCompatActivity
import com.zhusx.core.imp.SimpleRecyclerAdapter
import com.zhusx.core.interfaces.IHttpResult
import com.zhusx.core.network.HttpRequest
import com.zhusx.core.utils._Views
import echat.future.cn.echat.R
import echat.future.cn.echat.home.bean.*
import echat.future.cn.echat.home.network.LoadData
import echat.future.cn.echat.home.network.SimpleHttpListener
import echat.future.cn.echat.home.tools.loadHeaderImage
import echat.future.cn.echat.my.utils.StatusBarUtils
import echat.future.cn.echat.my.utils.UserHelper
import echat.future.cn.echat.netease.NeteaseLoginUtil
import echat.future.cn.echat.video.MyVideoActivity
import jp.wasabeef.glide.transformations.BlurTransformation
import kotlinx.android.synthetic.main.activity_anchor_home.*
import lumingweihua.future.cn.baselibgxh.base.MyApplication

/**
 *
 * Author  zhusx
 * Email   327270607@qq.com
 * Create  2018/8/9 21:39
 */
abstract class AnchorHomeBaseActivity : _BaseAppCompatActivity() {
    private var id: String? = null
    private val homeData by lazy {
        LoadData<AnchorEntity>(LoadData.Api.某个主播详情, this)
                .apply {
                    _setOnLoadingListener(object : SimpleHttpListener<AnchorEntity>() {
                        override fun onLoadComplete(api: LoadData.Api, request: HttpRequest<Any>, result: IHttpResult<AnchorEntity>) {
                            if (this@AnchorHomeBaseActivity.isDestroyed) {
                                return
                            }
                            initView(result.data)
                        }
                    })
                }
    }
    private val videoData by lazy {
        LoadData<AnchorVideoEntity>(LoadData.Api.主播的小视频, this)
                .apply {
                    _setOnLoadingListener(object : SimpleHttpListener<AnchorVideoEntity>() {
                        override fun onLoadComplete(api: LoadData.Api, request: HttpRequest<Any>, result: IHttpResult<AnchorVideoEntity>) {
                            val list = mutableListOf<Video>()
                            if (result.data.free_video.isNotEmpty()) {
                                list.addAll(result.data.free_video)
                            }
                            if (result.data.pay_video.isNotEmpty()) {
                                list.addAll(result.data.pay_video)
                            }
                            recyclerView.adapter = object : SimpleRecyclerAdapter<Video>(R.layout.list_item_anchor, list) {
                                override fun __getEmptyLayoutResource() = R.layout.layout_empty
                                override fun bindViewHolder(holder: _ViewHolder, p1: Int, s: Video) {
                                    holder.setText(R.id.tv_sign, data!!.sign)
                                    holder.setText(R.id.tv_name, data!!.username)
                                    holder.setText(R.id.tv_fans, "${s.colletion_num}")
                                    holder.getView<ImageView>(R.id.iv_header).loadHeaderImage(data!!.avatar)
//                                    Glide.with(this@AnchorHomeBaseActivity).load(s.img).into(holder.getView(R.id.iv_image))
                                    if (s.type == 1){
                                        Glide.with(this@AnchorHomeBaseActivity)
                                                .load(s.img)
                                                .into(holder.getView(R.id.iv_image))
                                    }else{
                                        Glide.with(this@AnchorHomeBaseActivity)
                                                .load(s.img)
                                                .apply(bitmapTransform( BlurTransformation(25
                                                        , 15)))
                                                .into(holder.getView(R.id.iv_image))
                                    }


                                    holder.rootView.setOnClickListener {

                                        if (id == UserHelper.getUserId()) {
//                                            startActivity(Intent(it.context, PlayVideoActivity::class.java)
//                                                    .putExtra("title", data?.username)
//                                                    .putExtra("image", s.img)
//                                                    .putExtra("url", s.video))
                                            startActivity(Intent(it.context, MyVideoActivity::class.java)
                                                    .putExtra("member_id", id)
                                                    .putExtra("vid", s.id))
                                            return@setOnClickListener
                                        }
                                        if (s.type == 1 || s.can_see == 1) {
                                            startActivity(Intent(it.context, MyVideoActivity::class.java)
                                                    .putExtra("member_id", id)
                                                    .putExtra("vid", s.id))
//                                            startActivity(Intent(it.context, PlayVideoActivity::class.java)
//                                                    .putExtra("title", data?.username)
//                                                    .putExtra("image", s.img)
//                                                    .putExtra("url", s.video))
                                        } else {
                                            video = s
                                            onItemPlayVideo(s, result.data.video_price)
                                        }
                                    }
                                }
                            }
                        }
                    })
                }
    }
    private val allowData by lazy {
        LoadData<AnchorVideoEntity>(LoadData.Api.关注主播, this)
                .apply {
                    _setOnLoadingListener(object : SimpleHttpListener<AnchorVideoEntity>() {
                        override fun onLoadComplete(api: LoadData.Api, request: HttpRequest<Any>, result: IHttpResult<AnchorVideoEntity>) {

                            if (data!!.focus_status == 0) {
                                data!!.focus_status = 1
                                tv_allow.setBackgroundResource(R.drawable.shiping_quxiao)
                                tv_allow.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0)
                                tv_allow.text = "取消关注"
                                _showToast("关注成功")
                            } else {
                                data!!.focus_status = 0
                                tv_allow.text = "关注"
                                _showToast("取消关注成功")
                                tv_allow.setCompoundDrawablesWithIntrinsicBounds(R.drawable.shiping_guanzhu, 0, 0, 0)
                                tv_allow.setBackgroundResource(R.drawable.shiping_guanzhu_di)
                            }
                        }
                    })
                }
    }
    private val dearData by lazy {
        LoadData<List<DearEntity>>(LoadData.Api.用户亲密榜, this)
                .apply {
                    _setOnLoadingListener(object : SimpleHttpListener<List<DearEntity>>() {
                        override fun onLoadComplete(api: LoadData.Api, request: HttpRequest<Any>, result: IHttpResult<List<DearEntity>>) {
                            result.data?.forEachIndexed { i, item ->
                                if (this@AnchorHomeBaseActivity.isDestroyed) {
                                    return
                                }
                                if (i == 0) {
                                    iv_dear_1.loadHeaderImage(item.user_avatar)
                                } else if (i == 1) {
                                    iv_dear_2.loadHeaderImage(item.user_avatar)
                                } else if (i == 2) {
                                    iv_dear_3.loadHeaderImage(item.user_avatar)
                                } else {
                                    return
                                }
                            }
                        }
                    })
                }
    }
    private val liwuData by lazy {
        LoadData<PresentEntity>(LoadData.Api.用户礼物柜, this)
                .apply {
                    _setOnLoadingListener(object : SimpleHttpListener<PresentEntity>() {
                        override fun onLoadComplete(api: LoadData.Api, request: HttpRequest<Any>, result: IHttpResult<PresentEntity>) {
                            tv_liwu_count.text = "${result.data.total}"
                            if (this@AnchorHomeBaseActivity.isDestroyed) {
                                return
                            }
                            result.data.list?.forEachIndexed { i, item ->
                                if (i == 0) {
                                    iv_liwu_1.loadHeaderImage(item.present_img)
                                } else if (i == 1) {
                                    iv_liwu_2.loadHeaderImage(item.present_img)
                                } else if (i == 2) {
                                    iv_liwu_3.loadHeaderImage(item.present_img)
                                } else {
                                    return
                                }
                            }
                        }
                    })
                }
    }
    private val payData by lazy {
        LoadData<Void>(LoadData.Api.观看付费视频, this)
                .apply {
                    _setOnLoadingListener(object : SimpleHttpListener<Void>() {
                        override fun onLoadComplete(api: LoadData.Api, request: HttpRequest<Any>, result: IHttpResult<Void>) {
                            if (this@AnchorHomeBaseActivity.isDestroyed) {
                                return
                            }
                            _showToast("购买成功")
                            video?.can_see = 1
//                            startActivity(Intent(this@AnchorHomeBaseActivity, PlayVideoActivity::class.java)
//                                    .putExtra("title", data?.username)
//                                    .putExtra("image", video!!.img)
//                                    .putExtra("url", video!!.video))
                            startActivity(Intent(this@AnchorHomeBaseActivity, MyVideoActivity::class.java)
                                    .putExtra("member_id", id)
                                    .putExtra("vid", video?.id))
                        }
                    })
                }
    }
    private var video: Video? = null
    private var data: AnchorEntity? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        StatusBarUtils.hideStatus(this)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_anchor_home)
        id = intent.getStringExtra(_EXTRA_String_ID)
        homeData._loadData(id)
        videoData._loadData(id)
        dearData._loadData(id)
        liwuData._loadData(id)
        iv_return.setOnClickListener { finish() }
    }

    abstract fun onLoadSuccess(id: String, data: AnchorEntity)
    abstract fun onItemPlayVideo(video: Video, price: String)

    private fun initView(data: AnchorEntity) {
        this.data = data
        tv_allow.visibility = View.VISIBLE
        viewPager.adapter = object : _BasePagerAdapter<String>(data.author_img) {
            override fun getView(inflater: LayoutInflater, p1: Int, s: String, p3: View?, p4: ViewGroup?): View {
                val imageView = ImageView(inflater.context).also {
                    it.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
                    it.scaleType = ImageView.ScaleType.FIT_XY
                }
                Glide.with(this@AnchorHomeBaseActivity).load(s).into(imageView)
                return imageView
            }
        }
        banner.attachToViewpager(viewPager)
        radioGroup.setOnCheckedChangeListener { group, checkedId ->
            when (checkedId) {
                R.id.radio_1 -> {
                    layout_yinsi.visibility = View.VISIBLE
                    recyclerView.visibility = View.GONE
                }
                R.id.radio_2 -> {
                    layout_yinsi.visibility = View.GONE
                    recyclerView.visibility = View.VISIBLE
                }
            }
        }
        tv_title.text = data.username
        tv_name.text = data.username
        tv_fans.text = "${data.fans} 粉丝"
        tv_city.text = data.city
        tv_height.text = "${data.height}"
        tv_weight.text = "${data.weight}"
        tv_constellation.text = "${data.constellation}"
        tv_price.text = "${data.price}E币/分钟"
        tv_sign.text = "${data.sign ?: ""}"
        tv_sign2.text = "${data.sign ?: ""}"
        data.apperance?.forEachIndexed { i, item ->
            if (i == 0) {
                tv_my_label1.text = item.sign
                tv_my_label1.toCornersDrawable(item.color)
            } else if (i == 1) {
                tv_my_label2.text = item.sign
                tv_my_label2.toCornersDrawable(item.color)
            }
        }
        when (data.last_status ?: "") {
            "0" -> {
                tv_last_status.text = "离线"
                tv_status.setImageResource(R.drawable.btn_lixian)
            }
            "1" -> {
                tv_last_status.text = "在线"
                tv_status.setImageResource(R.drawable.btn_zaixian)
            }
            "2" -> {
                tv_last_status.text = "在聊"
                tv_status.setImageResource(R.drawable.btn_zailiao)
            }
            else -> {
                tv_last_status.text = "未知"
                tv_status.setImageResource(R.drawable.btn_lixian)
            }
        }
//        when (data?.level ?: "") {
//            "2" -> {
        iv_level.setImageResource(R.drawable.btn_renzheng)
//            }
//        }
        when (data.gj ?: "") {
            "yg" -> {
                iv_gj.setImageResource(R.drawable.btn_guan_yin)
            }
            "jg" -> {
                iv_gj.setImageResource(R.drawable.btn_guan_huang)
            }
            "cg" -> {
                iv_gj.setImageResource(R.drawable.btn_guan_cai)
            }
            else -> {
                iv_gj.setImageResource(R.drawable.btn_guan_yin)
            }
        }
        when (data.focus_status) {
            0 -> {
                tv_allow.text = "关注"
                tv_allow.setCompoundDrawablesWithIntrinsicBounds(R.drawable.shiping_guanzhu, 0, 0, 0)
                tv_allow.setBackgroundResource(R.drawable.shiping_guanzhu_di)
            }
            1 -> {
                tv_allow.setBackgroundResource(R.drawable.shiping_quxiao)
                tv_allow.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0)
                tv_allow.text = "取消关注"
            }
            else -> {
                tv_allow.visibility = View.GONE
            }
        }
        tv_allow.setOnClickListener {
            if (id == UserHelper.getUserId()) {
                _showToast("不能关注自己")
                return@setOnClickListener
            }
            allowData._loadData(id, if (data.focus_status == 0) 1 else 3)
        }
        tv_like.text = "${data.like}"
        tv_unlike.text = "${data.unlike}"
        tv_answer_rate.text = "${data.answer_rate}"
        data.comment?.forEach {
            val v = LayoutInflater.from(this@AnchorHomeBaseActivity).inflate(R.layout.item_list_anchor_comment, null, false)
            v.findViewById<ImageView>(R.id.iv_image).loadHeaderImage(it.user_avatar)
            v.findViewById<TextView>(R.id.tv_name).text = it.username
            v.findViewById<TextView>(R.id.tv_level).text = "LV.${it.level ?: "0"}"
            it.reply_tag?.forEachIndexed { index, replyTag ->
                if (index == 0) {
                    v.findViewById<TextView>(R.id.tv_tag1).text = replyTag.tag_name
                    v.findViewById<TextView>(R.id.tv_tag1).toCornersDrawable(replyTag.value)
                    tv_ta_label1.text = replyTag.tag_name
                    tv_ta_label1.toCornersDrawable(replyTag.value)
                } else if (index == 1) {
                    v.findViewById<TextView>(R.id.tv_tag2).text = replyTag.tag_name
                    v.findViewById<TextView>(R.id.tv_tag1).toCornersDrawable(replyTag.value)
                    tv_ta_label2.text = replyTag.tag_name
                    tv_ta_label2.toCornersDrawable(replyTag.value)
                }
            }
            layout_comment.addView(v)
        }
        layout_ta_label.setOnClickListener { startActivity(Intent(this@AnchorHomeBaseActivity, TaLabelActivity::class.java).putExtra(_EXTRA_String_VALUE, Gson().toJson(data))) }
        layout_liwu.setOnClickListener { startActivity(Intent(this@AnchorHomeBaseActivity, GiftTotalActivity::class.java).putExtra(_EXTRA_String_ID, id)) }
        layout_qinmi.setOnClickListener { startActivity(Intent(this@AnchorHomeBaseActivity, DearRankingActivity::class.java).putExtra(_EXTRA_String_ID, id)) }
        val currentHeaderHeight = _Views.dip2px(350f)
        scrollView.setOnScrollChangeListener { v: NestedScrollView?, scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int ->
            if (scrollY <= currentHeaderHeight) {
                layout_title.alpha = (scrollY) * 1f / currentHeaderHeight
            } else if (scrollY > currentHeaderHeight) {
                layout_title.alpha = 1f
            }
        }
        tv_im.setOnClickListener {
            if (id == UserHelper.getUserId()) {
                _showToast("不能和自己私信")
                return@setOnClickListener
            }
            if (data.is_black == 1) {
                _showToast("黑名单不允许私聊")
                return@setOnClickListener
            }
            //私信
            startActivity(Intent(this@AnchorHomeBaseActivity, ChatActivity::class.java)
                    .putExtra("id", data.mobile)
                    .putExtra("avatar", data.avatar)
                    .putExtra("username", data.username)
            )
        }
        onLoadSuccess(id!!, data)
    }

    fun TextView.toCornersDrawable(color: String) {
        val drawable = GradientDrawable()
        drawable.cornerRadius = _Views.dip2px(20.toFloat()).toFloat()
        try {
            drawable.setColor(Color.parseColor(color))
        } catch (e: Exception) {
            drawable.setColor(Color.parseColor("#FF759F"))
        }
        this.setBackgroundDrawable(drawable)
    }

    fun payECoin(video_id: String) {
        payData._loadData(id, video_id)
    }
}